﻿using OaEntity.Models;
using PermissionAuthenticationDemo.Common;
using PermissionAuthenticationDemo.Config;
using PermissionAuthenticationDemo.Utility.Service;

namespace PermissionAuthenticationDemo.Service.Impl
{
    public class UserServiceImpl : IUserService
    {
        public readonly OaContext oaContext;
        private readonly IJWTService _IJWTService;

        public UserServiceImpl(OaContext oaContext, IJWTService jWTService)
        {
            this.oaContext = oaContext;
            this._IJWTService = jWTService;
        }

        public LoginResult<Tcauser> GetToken(string userName, string passWord)
        {
            try
            {
                string name = userName ?? throw new Exception("获取用户名失败");
                string password = passWord ?? throw new Exception("获取密码失败");

                //将密码转为md5
                ToMD5<string> toMd5 = new ToMD5<string>();
                var passwordMD5 = toMd5.GetMD5Dat(passWord);

                var user = oaContext.Tcausers.Where(x => x.UserName == name && x.Password == passwordMD5).FirstOrDefault();

                if (user != null)
                {
                    var userID = user.UserId;
                    //获取token，同时返回用户的属性
                    var token = this._IJWTService.GetToken(userID);

                    //不能将密码返回
                    return LoginResult<Tcauser>.Success(
                        new Tcauser
                        {
                            UserId = user.UserId,
                            UserName = user.UserName,
                            Phone = user.Phone,
                            Email = user.Email,
                            Status = user.Status,
                            IsDelete = user.IsDelete,
                            Operater = user.Operater,
                            OperateTime = user.OperateTime
                        }, "登录成功", token);
                }
                else
                {
                    return LoginResult<Tcauser>.Error(user, "登录失败");
                }
            }catch (Exception e)
            {
                throw new Exception("无效用户");
            }
            
        }
    }
}
